package com.sls.web.manager.action.recharge;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionContext;
import com.sls.core.common.CommonUtil;
import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.page.Pagination;
import com.sls.web.manager.recharge.pojo.PhoneArea;
import com.sls.web.manager.recharge.querybean.PhoneAreaQuery;
import com.sls.web.manager.recharge.service.PhoneAreaService;

/**
 * @author sxf
 * 
 */
public class PhoneAreaAction extends SuperAction {
	private static final long serialVersionUID = 3045994553824195440L;

	@Resource(name = "phoneAreaService")
	private PhoneAreaService phoneAreaService;

	// 页面使用
	private PhoneArea phoneArea;

	private String phone;

	private Pagination<PhoneArea> page;
	private PhoneAreaQuery phoneAreaQuery;

	// 是否编辑页面
	// private Boolean isEdit;
	// 是否添加页面
	private Boolean isAdd;

	public String search() throws Exception {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		if (StringUtils.isNotBlank(phone)) {
			Matcher m = p.matcher(phone);
			if (m.matches()) {
				PhoneAreaQuery query = new PhoneAreaQuery();
				query.setPhone(phone);
				PhoneArea queryPhoneArea = phoneAreaService.queryOne(query,
						getCurrentOperator());
				if (queryPhoneArea != null) {
					phoneArea = queryPhoneArea;
				} else {
					phoneArea = searchFromInternet(phone);
					phoneArea.setUpdateOperator(getCurrentOperator()
							.getUserId());
					phoneAreaService.insert(phoneArea, getCurrentOperator());
				}
			}
		}

		return "search";
	}

	@SuppressWarnings("unchecked")
	public String list() throws Exception {
		// 查询cardInfo
		if (phoneAreaQuery == null) {
			phoneAreaQuery = new PhoneAreaQuery();
			phoneAreaQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			phoneAreaQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		if (StringUtils.isNotBlank(phone)) {
			phoneAreaQuery.setPhone(phone);
		}
		page = phoneAreaService.queryPage(phoneAreaQuery, getCurrentOperator());
		if (page != null && page.getList().isEmpty()) {
			search();
			page.getList().add(phoneArea);
			Map<String, Object> request = (Map<String, Object>) ActionContext
					.getContext().get("request");
			request.put("tip", "数据库中没有找到相关数据,使用站外数据");
		}

		return "list";
	}

	public String add() throws Exception {
		isAdd = true;
		return "add";
	}

	public String toEdit() throws Exception {
		isAdd = false;
		PhoneAreaQuery query = new PhoneAreaQuery();
		if (phone == null) {
			phone = "";
		}
		query.setPhone(phone);
		PhoneArea queryArea = phoneAreaService.queryOne(query,
				getCurrentOperator());
		if (queryArea != null) {
			phoneArea = queryArea;
		}

		return "edit";
	}

	public String doAddOrEdit() throws Exception {
		if (phoneArea != null) {
			PhoneAreaQuery query = new PhoneAreaQuery();
			query.setPhone(phoneArea.getPhone());
			PhoneArea queryArea = phoneAreaService.queryOne(query,
					getCurrentOperator());
			if (queryArea != null) {
				phoneAreaService.update(phoneArea, getCurrentOperator());
			} else {
				phoneAreaService.insert(phoneArea, getCurrentOperator());
			}
		}
		redirectionUrl = "phone_area!list.htm";
		return SUCCESS;
	}

	public String delete() throws Exception {
		if (StringUtils.isNotBlank(phone)) {
			PhoneArea info = new PhoneArea();
			info.setPhone(phone);
			phoneAreaService.delete(info, getCurrentOperator());
		}
		redirectionUrl = "phone_area!list.htm";
		return SUCCESS;
	}

	public PhoneArea searchFromInternet(String phone) throws Exception {
		String baseUrl = "http://api.showji.com/Locating/20080808.aspx?m="
				+ phone + "&output=json";
		URL url = new URL(baseUrl);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
		// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true, 默认情况下是false;
		// httpUrlConnection.setDoOutput(true);
		// 设置是否从httpUrlConnection读入，默认情况下是true;
		httpUrlConnection.setDoInput(true);
		// Post 请求不能使用缓存
		// httpUrlConnection.setUseCaches(false);

		// 设定传送的内容类型是可序列化的java对象
		// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
		httpUrlConnection.setRequestProperty("Content-Type",
				"text/html; charset=utf-8");
		httpUrlConnection
				.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1");
		// 设定请求的方法为"POST"，默认是GET
		// httpUrlConnection.setRequestMethod("POST");
		// 连接，从上述第2条中url.openConnection()至此的配置必须要在connect之前完成，
		httpUrlConnection.connect();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpUrlConnection.getInputStream())); // 实例化输入流，并获取网页代码
		String s; // 依次循环，至到读的值为空
		StringBuilder sb = new StringBuilder();
		while ((s = reader.readLine()) != null) {
			sb.append(s);
		}
		reader.close();
		// {"Mobile":"13758987548","QueryResult":"True","Province":"浙江","City":"金华",
		// "AreaCode":"0579","PostCode":"321000","Corp":"中国移动","Card":"GSM"}
		String result = sb.toString();
		PhoneArea pa = null;
		if (StringUtils.isNotBlank(result)) {
			Gson gson = CommonUtil.gson();
			Map<String, String> map = gson.fromJson(result,
					new TypeToken<StringMap<String>>() {
					}.getType());
			String phoneResult = map.get("Mobile");// 所查号码
			String province = map.get("Province");// 归属省份
			String city = map.get("City");// 归属城市
			String corp = map.get("Corp");// 运营商
			// String card = map.get("Card");// 卡类型			
			pa = new PhoneArea();
			pa.setPhone(phoneResult);
			pa.setProvince(province);
			pa.setCity(city);
			pa.setType(corp);
		}

		return pa;
	}

	public static void main(String[] args) throws Exception {
		PhoneAreaAction p = new PhoneAreaAction();
		p.searchFromInternet("18695487859");
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Pagination<PhoneArea> getPage() {
		return page;
	}

	public void setPage(Pagination<PhoneArea> page) {
		this.page = page;
	}

	public PhoneAreaQuery getPhoneAreaQuery() {
		return phoneAreaQuery;
	}

	public void setPhoneAreaQuery(PhoneAreaQuery phoneAreaQuery) {
		this.phoneAreaQuery = phoneAreaQuery;
	}

	public Boolean getIsAdd() {
		return isAdd;
	}

	public void setIsAdd(Boolean isAdd) {
		this.isAdd = isAdd;
	}

	public PhoneArea getPhoneArea() {
		return phoneArea;
	}

	public void setPhoneArea(PhoneArea phoneArea) {
		this.phoneArea = phoneArea;
	}
}
